<template>
  <div style="height: 10vh;background-color:#fff;padding:10px 20px;">
    <el-card style="height: 100%;">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" @submit.prevent="queryForm" class="searchForm">
        <el-form-item label="停车场" prop="parkName">
          <el-select v-model="searchForm.parkName" placeholder="请选择停车场" filterable clearable>
            <el-option v-for="item in parkOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-select v-model="searchForm.phone" placeholder="请选择手机号" filterable clearable>
            <el-option v-for="item in phoneOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号" prop="carCode">
          <el-select v-model="searchForm.carCode" placeholder="请选择车牌号" filterable clearable>
            <el-option v-for="item in carCodeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="长租方式" prop="rentMode">
          <el-select v-model="searchForm.rentMode" placeholder="请选择长租方式" filterable clearable>
            <el-option v-for="mode in rentModes" :key="mode.value" :label="mode.label" :value="mode.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否有效" prop="isValid">
          <el-select v-model="searchForm.isValid" placeholder="请选择是否有效" filterable clearable>
            <el-option label="有效" value="有效" />
            <el-option label="无效" value="无效" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="选择开始时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" :loading="loading" @click="queryForm">查询</el-button>
          <el-button type="primary" @click="openDialog('create')">新建</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40vh" @close="resetDialogForm">
    <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="8vh" label-position="left" class="dialogForm">
      <el-row style="display: flex; flex-direction: column; align-items: center;" :gutter="10">
      <el-form-item label="停车场名称" prop="parkName">
        <el-select v-model="dialogForm.parkName" placeholder="请选择停车场名称" filterable>
          <el-option v-for="park in parkList" :key="park.value" :label="park.label" :value="park.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="dialogForm.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="车牌号" prop="carCode">
        <el-input v-model="dialogForm.carCode" placeholder="请输入车牌号" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
            v-model="dialogForm.startTime"
            type="date"
            placeholder="选择开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="updateEndTime"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
            v-model="dialogForm.endTime"
            type="date"
            placeholder="选择结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="长租方式" prop="rentMode">
        <el-select
            v-model="dialogForm.rentMode"
            placeholder="请选择长租方式"
            @change="updateEndTime"
        >
          <el-option v-for="mode in rentModes" :key="mode.value" :label="mode.label" :value="mode.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="计费规则" prop="billRule">
        <el-select
            v-model="dialogForm.billRule"
            placeholder="请选择计费规则"
        >
          <el-option
              v-for="rule in filteredBillRules"
              :key="rule.ruleNum"
              :label="rule.ruleName"
              :value="rule.ruleName"
          >
            <el-tooltip :content="`租金: ${rule.rentFee}元`" placement="top">
              <span>{{ rule.ruleName }}</span>
            </el-tooltip>
          </el-option>
        </el-select>
      </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: center; gap: 20px;">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" :loading="saving" @click="saveDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <div class="table-container">
      <el-table
          :data="recordList"
          border
          v-loading="loading"
          ref="tableRef"
      >
        <el-table-column prop="parkName" label="停车场" align="center" />
        <el-table-column prop="phone" label="手机号" align="center" />
        <el-table-column prop="carCode" label="车牌号" align="center" />
        <el-table-column prop="rentMode" label="长租方式" align="center" />
        <el-table-column prop="billRule" label="计费规则" align="center" />
        <el-table-column prop="startTime" label="开始时间" align="center" />
        <el-table-column prop="endTime" label="结束时间" align="center" />
        <el-table-column prop="isValid" label="是否有效" align="center" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { DateTime } from 'luxon';
import { logOperation } from '@/utils/log';

const API_URL = import.meta.env.VITE_API_BASE_URL;

const rentModes = ref([
  { label: '月租', value: '月租' },
  { label: '年租', value: '年租' }
]);

const billRules = ref([]);

// 过滤计费规则，根据选择的 rentMode 动态显示
const filteredBillRules = computed(() => {
  if (!dialogForm.value.rentMode) return billRules.value; // 未选择时显示所有规则
  return billRules.value.filter(rule => rule.rentMode === dialogForm.value.rentMode);
});

// 获取计费规则数据
const fetchBillRules = async () => {
  try {
    const response = await axios.get(`${API_URL}/v1/bill-long-rule/select`, { // 调整为正确的接口
      params: { page: 1, size: 1000 } // 获取所有规则
    });
    const data = response.data;
    if (data.code === 2000) {
      billRules.value = data.response.map(item => ({
        ruleNum: item.ruleNum,
        ruleName: item.ruleName,
        rentMode: item.rentMode,
        rentFee: item.rentFee
      }));
    }
  } catch (error) {
    console.error('Fetch Bill Rules Error:', error);
    ElMessage.error('获取计费规则失败');
  }
};

const parkList = ref([]);
const parkOptions = ref([]);
const phoneOptions = ref([]);
const carCodeOptions = ref([]);

const searchForm = ref({
  parkName: null,
  phone: null,
  carCode: null,
  rentMode: null,
  isValid: null,
  startTime: null,
  endTime: null
});
const searchFormRef = ref(null);

const recordList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取停车场数据
const fetchParkLots = async () => {
  try {
    const response = await axios.get(`${API_URL}/v1/parklot/select`);
    const data = response.data;
    if (data.code === 2000) {
      parkList.value = data.response.map(item => ({
        value: item.parkName,
        label: item.parkName
      }));
    }
  } catch (error) {
    console.error('Fetch Parklots Error:', error);
    ElMessage.error('获取停车场数据失败');
  }
};

// 获取搜索选项
const fetchSearchOptions = async () => {
  try {
    const response = await axios.get(`${API_URL}/v1/userParkRecord/options`);
    const data = response.data;
    if (data.code === 2000) {
      parkOptions.value = (data.response.parkNames || []).map(item => ({ value: item, label: item }));
      phoneOptions.value = (data.response.phones || []).map(item => ({ value: item, label: item }));
      carCodeOptions.value = (data.response.carCodes || []).map(item => ({ value: item, label: item }));
    }
  } catch (error) {
    console.error('Fetch Search Options Error:', error);
    ElMessage.error('获取搜索选项数据失败');
  }
};

// 查询记录
const queryForm = async () => {
  loading.value = true;
  try {
    const params = {
      parkName: searchForm.value.parkName || null,
      phone: searchForm.value.phone || null,
      carCode: searchForm.value.carCode || null,
      rentMode: searchForm.value.rentMode || null,
      isValid: searchForm.value.isValid || null,
      startTime: searchForm.value.startTime || null,
      endTime: searchForm.value.endTime || null,
      page: currentPage.value,
      size: pageSize.value
    };
    const response = await axios.get(`${API_URL}/v1/userParkRecord/select`, { params });
    const data = response.data;

    if (data && data.code === 2000) {
      recordList.value = data.response || [];
      total.value = data.total || 0;
      await nextTick();
      ElMessage.success('数据加载成功');
    } else {
      ElMessage.error(`数据加载失败: ${data?.response?.message || '未知错误'}`);
      recordList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('Query Error:', error);
    ElMessage.error('查询请求异常');
    recordList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value = { parkName: null, phone: null, carCode: null, rentMode: null, isValid: null, startTime: null, endTime: null };
  currentPage.value = 1;
  queryForm();
};

const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogForm = ref({
  id: null,
  parkName: '',
  phone: '',
  carCode: '',
  rentMode: '月租',
  billRule: '',
  startTime: '',
  endTime: '',
  isValid: '有效'
});
const dialogFormRef = ref(null);

const carCodePattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](?:[A-HJ-NP-Z0-9]{5}|[DF][A-HJ-NP-Z0-9]{5})$/;
const dialogRules = ref({
  parkName: [{ required: true, message: '请选择停车场', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  carCode: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { pattern: carCodePattern, message: '请输入合法车牌号（燃油车6位或新能源7位）', trigger: 'blur' }
  ],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  rentMode: [{ required: true, message: '请选择长租方式', trigger: 'change' }],
  billRule: [{ required: true, message: '请选择计费规则', trigger: 'change' }]
});

const saving = ref(false);

const openDialog = (type, row = {}) => {
  dialogVisible.value = true;
  dialogTitle.value = type === 'create' ? '新增长租记录' : '编辑长租记录';
  dialogForm.value = type === 'create'
      ? { id: null, parkName: '', phone: '', carCode: '', rentMode: '月租', billRule: '', startTime: '', endTime: '', isValid: '有效' }
      : { ...row };
};

const resetDialogForm = () => {
  dialogFormRef.value?.resetFields();
};

const updateEndTime = () => {
  if (!dialogForm.value.startTime || !dialogForm.value.rentMode) return;
  const startDate = DateTime.fromFormat(dialogForm.value.startTime, 'yyyy-MM-dd');
  let endDate;
  if (dialogForm.value.rentMode === '月租') {
    endDate = startDate.plus({ days: 31 });
  } else if (dialogForm.value.rentMode === '年租') {
    endDate = startDate.plus({ days: 365 });
  }
  if (endDate) {
    dialogForm.value.endTime = endDate.toFormat('yyyy-MM-dd');
  }
};

const saveDialog = async () => {
  dialogFormRef.value.validate(async (valid) => {
    if (!valid) return;
    saving.value = true;
    try {
      const url = `${API_URL}/v1/userParkRecord/save`;
      const response = await axios.post(url, dialogForm.value);
      if (response.data.code === 2000) {
        ElMessage.success(dialogForm.value.id ? '更新成功' : '新建成功');
        dialogVisible.value = false;
        await queryForm();
        await logOperation('长租记录', `${dialogForm.value.id ? '更新' : '新建'}长租记录 ${dialogForm.value.phone} ${dialogForm.value.carCode}`);
      } else {
        ElMessage.error(`保存失败: ${response.data?.response?.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('Save Error:', error);
      ElMessage.error('保存请求异常');
    } finally {
      saving.value = false;
    }
  });
};

const closeDialog = () => {
  ElMessageBox.confirm('您确认要关闭本弹窗吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        dialogVisible.value = false;
      })
      .catch(() => {});
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryForm();
};

onMounted(() => {
  fetchParkLots();
  fetchSearchOptions();
  fetchBillRules();
  queryForm();
});
</script>

<style scoped>
.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px;
}

.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px;
}

.searchForm :deep(.el-select) {
  width: 15vh;
}

.searchForm :deep(.el-date-picker) {
  width: 15vh;
}

.dialogForm :deep(.el-select) {
  width: 20vh;
}
.dialogForm :deep(.el-input) {
  width: 20vh;
}
.dialogForm :deep(.el-date-picker) {
  width: 20vh;
}

</style>